<template>
  <a-card>
    <a-button type="primary" style="margin-bottom: 10px" @click="addTag()">新增标签</a-button>
    <!-- 表格 -->
    <a-table 
      :columns="columns" 
      :dataSource="tagList" 
      :pagination="pagination" 
      @change="changepage"
      :scroll="{ y: 600 }"
    >
      <template #bodyCell="{ column, record, index, text }">
        <!-- 序号插槽 -->
        <template v-if="column.key == 'index'">
          {{ (pagination.current - 1) * pagination.pageSize + parseInt(index) + 1 }}
        </template>

        <!-- 标签插槽 -->
        <template v-else-if="column.key == 'name'">
          <div class="editable-cell beyond_hiding">
            <div v-if="editableData['name:' + record.tagId]" class="editable-cell-input-wrapper">
              <a-input
                v-model:value="editableData['name:' + record.tagId].name"
                @pressEnter="renameTagName(record.tagId)"
              />
              <check-outlined class="editable-cell-icon-check" @click="renameTagName(record.tagId)" />
            </div>
            <div v-else class="editable-cell-text-wrapper">
              {{ text || ' ' }}
              <edit-outlined class="editable-cell-icon" @click="rename('name:' + record.tagId)" />
            </div>
          </div>
        </template>
        <!-- 用户插槽 -->
        <template v-else-if="column.key == 'users'">
          <div class="beyond_hiding">
            <a-tooltip color="#ffffff" placement="topLeft">
              <template #title>
                <a-tag v-for="(item, index) in record.users ? record.users.split(',') : ''" :key="index">
                  <user-outlined />
                  {{ item }}
                </a-tag>
              </template>
              <a-tag v-for="(item, index) in record.users ? record.users.split(',') : ''" :key="index">
                <user-outlined />
                {{ item }}
              </a-tag>
            </a-tooltip>
          </div>
        </template>

        <!-- 编辑插槽 -->
        <template v-else-if="column.dataIndex === 'edit'">
          <div class="beyond_hiding">
            <a-divider type="vertical" />
            <a style="color: #2196f8" @click="edit(record)">编辑</a>
            <a-divider type="vertical" />
            <Popconfirm
              title="确定要删除吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="delTag(record)"
            >
              <a style="color: #2196f8">删除</a>
            </Popconfirm>
          </div>
          
        </template>
      </template>
    </a-table>

    <!-- 新增框 -->
    <a-modal
      title="新增标签"
      :visible="renameVisible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="cancel"
    >
      <a-input placeholder="请输入标签名称" v-model:value="saveParam.name" allowClear>
        <template #prefix>
          <SearchOutlined />
        </template>
      </a-input>
    </a-modal>

    <!-- 编辑框 -->
    <a-modal title="编辑标签" :visible="editVisible" @ok="editOk" @cancel="editCancel">
      <TagEdit :checkedKeys="editParam.userIds" @getValue="getSonValue"></TagEdit>
      <!-- <TreeList :checked-keys="editParam.userIds" @getValue="getSonValue"></TreeList> -->
    </a-modal>
  </a-card>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, UnwrapRef} from 'vue';
import { message, Popconfirm } from 'ant-design-vue';
import { SearchOutlined } from '@ant-design/icons-vue';
import { list, save, remove, addUserToTag, getUserIds } from '@/api/base/tag/tag';
import { APP_USER } from '@/enums/cacheEnum';
import { Storage } from '@/utils/Storage';
const tenantid = ref(Storage.Get(APP_USER).tenantid);
import TagEdit from '@/views/base/tag/tagEdit';
import TreeList from '@/components/basic/treeList.vue';
import { cloneDeep } from 'lodash-es';
defineOptions({
  name: 'tagList',
});
// 配置表头
const columns = [
  {
    title: '序号',
    width: 60,
    key: 'index',
    align: 'center',
    fixed: 'left',
  },
  {
    title: '标签',
    dataIndex: 'name',
    key: 'name',
    width: '150px',
    onFilter: (value: string, record: any) => record.name.indexOf(value) === 0,
    sorter: (a: any, b: any) => a.name.localeCompare(b.name), // 使用 localeCompare 进行字典顺序比较
    sortDirections: ['ascend', 'descend'], // 支持升序和降序
  },
  {
    title: '用户',
    dataIndex: 'users',
    key: 'users',
    width: '700px',
    align: 'left',
  },
  {
    title: '操作',
    dataIndex: 'edit',
    key: 'edit',
    fixed: 'right',
    width: 180,
    align: 'center',
  },
];

const editableData: UnwrapRef<Record<string, any>> = reactive({});

// 标签人员列表
const tagList = ref([]);
// 是否显示新增框
const renameVisible = ref(false);
// 点击新增按钮
const addTag = () => {
  renameVisible.value = true;
};
// 修改标签名
const rename = (key: string) => {
  let redKey = key.split(':')[1];
  editableData[key] = cloneDeep(tagList.value.filter(item => redKey == item.tagId)[0])
}
const renameTagName = async (tagId: string) => {
  const oldData = tagList.value.filter(item => tagId == item.tagId)[0]
  if(oldData.name == editableData['name:' + tagId].name) {
    message.info('未进行修改')
  } else {
    const renameParam = {
      tagId: editableData['name:' + tagId].tagId,
      name: editableData['name:' + tagId].name,
      tenantId: tenantid.value
    }
    console.log('renameParam',renameParam)
    await save(renameParam).then(res => {
      if(res.code == 0){
        message.success('修改成功')
      }else{
        message.error('修改失败')
      }
    })
    tagList.value.filter(item => tagId == item.tagId)[0].name = editableData['name:' + tagId].name
  }
  delete editableData['name:' + tagId]
}

const confirmLoading = ref<boolean>(false);
// 新增框确定
const handleOk = async () => {
  confirmLoading.value = true;
  await save(saveParam).then(res => {
    if (res.code == 0) {
      confirmLoading.value = false;
      renameVisible.value = false;
      message.success('新增成功');
    }
    else {
      message.error('新增失败')
    }
    getTagList();
  })
};

// 修改或保存标签参数
const saveParam = reactive({
  tagId: '',
  name: '',
  tenantId: tenantid.value,
});
// 关闭新增框
const cancel = () => {
  renameVisible.value = false;
};

// 是否显示编辑框
const editVisible = ref(false);
// 是否显示确认框
const visible = ref(false);
// 查询标签人员参数
const tagData = reactive({
  pageNumber: 1,
  pageSize: 20,
  f_tenantid: tenantid.value,
});
// 添加成员到标签参数
const editParam = reactive({});
// 点击编辑
const edit = (record) => {
  editVisible.value = true;
  editParam.tagId = record.tagId;
  const tagId = record.tagId;
  getUserIdsList(tagId);
};
// 关闭编辑框
const onClose = () => {
  editVisible.value = false;
};

// 获取标签列表
const getTagList = async () => {
  await list(tagData).then(res => {
    if (res.code == 0) {
      tagList.value = res.data.records;
      pagination.total = res.data.total;
    }
  });
};

// 删除标签
const delTag = async (record) => {
  const tagId = record.tagId;
  await remove({ tagId: tagId }).then(res =>{
    if (res.code == 0) {
      message.success('删除成功');
    } else {
      message.error('删除失败');
    }
    getTagList();
  });
};
// 编辑框确定
const editOk = async () => {
  await addUserToTag(editParam).then(res => {
    if (res.code == 0) {
      message.success('编辑成功');
      editVisible.value = false;
      
    }else {
      message.error('编辑失败');
    }
    getTagList();
  });
};
// 编辑框取消
const editCancel = () => {
  editVisible.value = false;
};

const tableChange = () => {
  tagData.pageNumber = pagination.current;
  tagData.pageSize = pagination.pageSize;
  getTagList();
};

// 接收子组件传过来的值
const getSonValue = (userIds) => {
  editParam.userIds = [...userIds];
};

// 查询当前标签人员列表
const getUserIdsList = async (tagId) => {
  const res = await getUserIds({ tagId: tagId });
  if (res.code == 0) {
    editParam.userIds = res.data;
  }
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  pageSizeOptions: ['10', '20', '30', '40'],
  showTotal: (total: number) => `共 ${total} 条`,
});

// 表格翻页
const changepage = (e) => {
  pagination.current = e.current;
  pagination.pageSize = e.pageSize;
  getTagList();
};

//
onMounted(() => {
  getTagList();
});
</script>
<style lang="less" scoped>
.editable-cell {
  position: relative;
  .editable-cell-input-wrapper,
  .editable-cell-text-wrapper {
    padding-right: 24px;
  }

  .editable-cell-text-wrapper {
    padding: 5px 24px 5px 5px;
  }

  .editable-cell-icon,
  .editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
  }

  .editable-cell-icon {
    margin-top: 4px;
    display: none;
  }

  .editable-cell-icon-check {
    line-height: 28px;
  }

  .editable-cell-icon:hover,
  .editable-cell-icon-check:hover {
    color: #108ee9;
  }

  .editable-add-btn {
    margin-bottom: 8px;
  }
}
.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}
.beyond_hiding {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  // display: block;
}
</style>



